package com.jpc.musicdelightapplication.ui.square.detail

import androidx.lifecycle.MutableLiveData
import com.jpc.lib_base.base.BaseViewModel
import com.jpc.lib_base.ext.handleRequest
import com.jpc.lib_base.ext.launch
import com.jpc.musicdelightapplication.data.DataRepository
import com.jpc.musicdelightapplication.data.bean.PlaylistData
import com.jpc.musicdelightapplication.data.bean.SongData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import top.wangchenyan.common.utils.ServerTime

class PlaylistDetailViewModel: BaseViewModel(){
    companion object{
        private const val SONG_LIST_LIMIT = 800
    }
    val playlistLiveData = MutableLiveData<PlaylistData?>()
    val songListLiveData = MutableLiveData<List<SongData>>()

    override fun start() {
    }


    fun fetchPlaylistAndSongList(playlistId: Long, realTimeData: Boolean){
        launch({
            val job1 = async(Dispatchers.IO + SupervisorJob()){
                DataRepository.getPlaylistDetail(playlistId)
            }
            val job2 = async(Dispatchers.IO + SupervisorJob()){
                val timestamp = if (realTimeData) ServerTime.currentTimeMillis() else null
                DataRepository.getPlaylistSongList(playlistId, limit = SONG_LIST_LIMIT, offset = 0, timestamp = timestamp)
            }
            try {
                val response1 = job1.await()
                val response2 = job2.await()
                val result1 = handleRequest(response1)
                val result2 = handleRequest(response2)
                if (result1.isSuccess && result2.isSuccess){
                    playlistLiveData.value = result1.getOrNull()?.data
                    songListLiveData.value = result2.getOrNull()?.data
                }
            }catch (e: Exception){
                e.printStackTrace()
            }
        })
    }
}